﻿using System;
using System.Data;
using System.Data.Entity;
using System.Data.Objects.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class ArticleController : BaseController
	{
		public ActionResult List(ArticleQueryModel model)
		{
			var articles = Db.Articles.Include(x => x.Channel).AsQueryable();
			if (!string.IsNullOrWhiteSpace(model.Keywords))
			{
				articles = articles.Where(x => x.Title.Contains(model.Keywords));
			}
			if (model.ChannelId.HasValue)
			{
				articles = articles.Where(x => x.ChannelId == model.ChannelId);
			}
			if (model.CreateTimeFrom.HasValue)
			{
				articles = articles.Where(x => SqlFunctions.DateDiff("d", model.CreateTimeFrom.Value, x.EditTime) >= 0);
			}
			if (model.CreateTimeTo.HasValue)
			{
				articles = articles.Where(x => SqlFunctions.DateDiff("d", model.CreateTimeTo.Value, x.EditTime) <= 0);
			}
			var currentPage = (model.PageNum ?? 1) - 1;
			var pageSize = model.NumPerPage ?? 20;

			ViewBag.ViewModel = new ArticleListViewModel
				{
					Channels = PopulateChannelsDropDownList(model.ChannelId, true),
					CurrentPageIndex = currentPage,
					PageSize = pageSize,
					TotalCount = articles.Count(),
					QueryModel = model
				};

			return View(articles);
		}

		public ActionResult Create()
		{
			var model = new Article
				{
					CreateTime = DateTime.Now,
					CreateUserId = User.UserId,
					EditTime = DateTime.Now,
					EditUserId = User.UserId
				};
			ViewBag.Channels = PopulateChannelsDropDownList();
			return View("Edit", model);
		}

		public ActionResult Edit(int id)
		{
			var model = Db.Articles.Single(x => x.Id == id);
			ViewBag.Channels = PopulateChannelsDropDownList(model.ChannelId);
			return View(model);
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Edit(Article model)
		{
			if (model.Id == 0)
			{
				//添加
				model.CreateTime = DateTime.Now;
				model.CreateUserId = User.UserId;
				model.EditTime = DateTime.Now;
				model.EditUserId = User.UserId;
				Db.Articles.Add(model);
			}
			else
			{
				//修改
				model.EditTime = DateTime.Now;
				model.EditUserId = User.UserId;
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();
			return JSuccess("操作成功！", "tab_cms_article");
		}

		public ActionResult Delete(int id)
		{
			var model = new Article {Id = id};
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", "tab_cms_article");
		}

		private SelectList PopulateChannelsDropDownList(object selectedItem = null, bool insertHeader = false)
		{
			var channels = Db.Channels.ToList().Select(x => new SelectListItem {Text = x.Name, Value = x.Id.ToString(CultureInfo.InvariantCulture)}).ToList();
			if (insertHeader)
			{
				channels.Insert(0, new SelectListItem {Text = "==所有频道==", Value = ""});
			}
			return new SelectList(channels, "Value", "Text", selectedItem);
		}

		/// <summary>
		/// 取消发布
		/// </summary>
		public ActionResult CancelPublish(int id)
		{
			var model = Db.Articles.FirstOrDefault(x => x.Id == id);
			if (model == null) return JError("您要取消发布的文章已丢失，请联系管理员！");

			model.Status = (int)ArticleStatus.Draft;
			Db.SaveChanges();

			return JSuccess("操作成功！", "tab_cms_article");
		}

		/// <summary>
		/// 重新发布
		/// </summary>
		public ActionResult RePublish(int id)
		{
			var model = Db.Articles.FirstOrDefault(x => x.Id == id);
			if (model == null) return JError("您要重新发布的文章已丢失，请联系管理员！");

			model.Status = (int)ArticleStatus.Published;
			Db.SaveChanges();

			return JSuccess("操作成功！", "tab_cms_article");
		}
	}
}